package com.ikun.kunpicturebackend.api.aliyunai.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ikun.kunpicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ikun.kunpicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ikun.kunpicturebackend.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 扩图API
 */
@Slf4j
@Component
public class AliYunAiApi {

    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    // 查询任务状态地址
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建发送扩图任务
     *
     * @param createOutPaintingTaskRequest 扩图请求
     * @return
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        ThrowUtils.throwIf(createOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR, "扩图参数为空");

        // 构造HTTP请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                // apiKey
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                // 开启异步处理
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));

        // 发送请求
        try (HttpResponse httpResponse = httpRequest.execute()) {
            // 异常判断
            if (!httpResponse.isOk()) {
                log.error("扩图请求异常：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败");
            }

            CreateOutPaintingTaskResponse taskResponse = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            String errCode = taskResponse.getCode();
            if (StrUtil.isNotBlank(errCode)) {
                log.error("AI 扩图失败，errorCode:{}, errorMessage:{}", errCode, taskResponse.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图接口响应异常");
            }

            return taskResponse;
        }
    }

    /**
     * 获取扩图结果
     * @param taskId 任务id
     * @return
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR, "任务id不能为空");

        // 查询扩图结果请求
        HttpRequest httpRequest = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey);

        try (HttpResponse httpResponse = httpRequest.execute()) {
            // 异常判断
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取扩图任务结果失败");
            }

            return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
        }

    }

}
